package com.example.springevent.service;

import com.example.springevent.event.AsyncEvent;
import com.example.springevent.event.GenericEvent;
import com.example.springevent.event.PayloadEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class EventDemoService {
    
    private final ApplicationEventPublisher eventPublisher;
    
    public void publishGenericEvent(String type, String message) {
        log.info("发布通用事件: 类型 = {}, 消息 = {}", type, message);
        
        Map<String, Object> data = new HashMap<>();
        data.put("message", message);
        data.put("timestamp", System.currentTimeMillis());
        
        eventPublisher.publishEvent(new GenericEvent<>(this, data, type));
    }
    
    public void publishPayloadEvent(String name, String payload) {
        log.info("发布Payload事件: 名称 = {}, 内容 = {}", name, payload);
        
        PayloadEvent event = new PayloadEvent(name, payload, System.currentTimeMillis());
        eventPublisher.publishEvent(event);
    }
    
    public void publishAsyncEvent(String message) {
        log.info("发布异步事件: 消息 = {}, 当前线程 = {}", 
                message, 
                Thread.currentThread().getName());
        
        eventPublisher.publishEvent(new AsyncEvent(this, message));
        
        log.info("异步事件已发布，继续执行");
    }
}